package cn.com.codes.userTag.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.com.codes.common.SecurityContextHolderHelp;
import cn.com.codes.framework.app.services.BaseServiceImpl;
import cn.com.codes.object.CasePubTag;
import cn.com.codes.object.UserTag;
import cn.com.codes.userTag.service.UserTagService;

public class UserTagServiceImpl extends BaseServiceImpl implements
		UserTagService {

	public String save(UserTag userTag){
		
		if(userTag.getTagName()!=null&&!"".equals(userTag.getTagName().trim())){
			//判断UserTag是否已存在
			String hql = "from UserTag ut where ut.userId=? and ut.tagName=? ";
			@SuppressWarnings("unchecked")
			List<UserTag> userTags = this.findByHql(hql, SecurityContextHolderHelp.getUserId(),userTag.getTagName());
			if(userTags != null && userTags.size() > 0){
				return "existed";
			}
			String sql = "delete from t_typedefine  where COMP_ID = '"+SecurityContextHolderHelp.getCompanyId()+"'  AND INDENTIFIER = 14 and STATUS_FLG='3'";
			this.getJdbcTemplateWrapper().getJdbcTemplate().execute(sql);//标签这前是逻辑删，这里先真删
			hql = " from CasePubTag where typeName=?  and compId=? and status!='3'";
			List<CasePubTag> CasePubTags = this.findByHql(hql, userTag.getTagName(),SecurityContextHolderHelp.getCompanyId());
			if(CasePubTags != null && CasePubTags.size() > 0){
				return "existed";
			}
			userTag.setUserId(SecurityContextHolderHelp.getUserId());
			this.add(userTag);
			return "success";
		}
		return "empty";
	}
	
	public List<UserTag> getUserTagsByUserId(String userId){

		
		String sql = "  SELECT\n" + 
				"	ut.tag_name\n" + 
				"FROM\n" + 
				"	t_user_tag ut\n" + 
				"WHERE\n" + 
				"	ut.user_id = '"+SecurityContextHolderHelp.getUserId()+"'\n" + 
				"UNION\n" + 
				"	SELECT\n" + 
				"		ty.ENUMNAME AS tag_name\n" + 
				"	FROM\n" + 
				"		t_typedefine ty\n" + 
				"	WHERE\n" + 
				"		ty.COMP_ID = '"+SecurityContextHolderHelp.getCompanyId()+"'\n" + 
				"	AND ty.INDENTIFIER = 14 and ty.STATUS_FLG='1'";
		List<UserTag> userTags = this.getJdbcTemplateWrapper().queryAllMatchListWithFreePra(sql, UserTag.class);
		if(userTags != null && userTags.size() > 0){
			return userTags;
		}
		return new ArrayList<UserTag>();
	}

}
